import sparkMD5 from 'spark-md5'

type MessageDataType = {
  file: File,
  start: number
  end: number
  chunk_size: number
}

export type FileChunkResult = {
  start: number
  end: number
  index: number
  chunk_hash: string
  blob: Blob
  percentage: number
}

async function createChunk(file: File, index: number, chunk_size: number): Promise<FileChunkResult> {
  return new Promise(resolve => {
    const start = index * chunk_size
    const end = Math.min(start + chunk_size, file.size)
    const spark = new sparkMD5.ArrayBuffer()
    const fileReader = new FileReader()
    const blob = file.slice(start, end)
    fileReader.onload = (e) => {
      spark.append(e.target?.result as ArrayBuffer)
      resolve({
        start,
        end,
        index,
        chunk_hash: spark.end(),
        blob,
        percentage: 0
      })
    }
    fileReader.readAsArrayBuffer(blob)
  })
}

self.onmessage = async e => {
  const { file, start, end, chunk_size } = e.data as MessageDataType
  const result = []
  for (let i = start; i < end; i++) {
    const prom = createChunk(file, i, chunk_size)
    result.push(prom)
  }
  const chunks = await Promise.all(result)
  postMessage(chunks)
}